package com.espirit.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.espirit.eap.manager.MessageViewType;
import com.espirit.eap.manager.workflow.WFInstanceService;
import com.espirit.eap.manager.workflow.WorkflowAware;
import com.espirit.eap.pagelayout.ModelService;
import com.espirit.eap.pagelayout.UrlUtil;
import com.espirit.eap.sa.LoginUser;
import com.espirit.eap.sa.LoginUserService;
import com.espirit.eap.util.StatGenericJPAService;
import com.espirit.eap.util.TxFileService;
import com.googlecode.cswish.Config;
import com.googlecode.cswish.annotation.GenericType;
import com.googlecode.cswish.annotation.ParamScope;
import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.model.ParameterMap;
import com.googlecode.cswish.model.Reference;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.oosearch.QLParse;
import com.googlecode.cswish.struts.hibernate.HibernateUtil;
import com.googlecode.cswish.struts.spring.ObjectFactory;
import com.googlecode.cswish.util.OgnlExUtil;
import com.opensymphony.xwork2.Result;

@Service
public class MessageService {
	
	@Resource
	protected StatGenericJPAService genericService;
	
	@Resource
	private ObjectFactory objectFactory;
	
	@Resource
	private ModelService modelService;
	
	@Resource
	protected OgnlExUtil ognlExUtil;
	
	@Resource
	protected LoginUserService loginUserService;
	
	@Resource
	protected Config config;
	
	@Resource
	protected QLParse qlParse;
	
	@Resource
	protected WFInstanceService wfInstanceService;
	
	@Resource
	protected UrlUtil urlUtil;
	
	@Resource
	private TxFileService txFileService;
	
	public void _search(@ParamScope(value = "#fn.newModel('com.espirit.common.Message')") Message model){
		model.setMessageViewType(MessageViewType.Normal);
	}
	
	public PageInfo search(ParameterMap model, int start, int limit,
    		String sort, String dir, boolean newSearch, Reference<QLInfo> qlInfoRef ,
    		@ParamScope(visible=false, value="#ps")PageElements ps ) {
	    if (StringUtils.isEmpty(sort)){
	    	sort = "a.createdOn";
	    } 
	    if (StringUtils.isEmpty(dir)){
	    	dir="desc";
	    }
	    if (newSearch){
	    	String messageViewType = model.getParameter("messageViewType", String.class);
	    	model.remove("messageViewType");
	    	if ("1".equals(messageViewType)){
	    		model.setParameter("hidden", true);
			} else if ("2".equals(messageViewType)){
			} else if ("0".equals(messageViewType)){
				model.setParameter("hidden", false);
			} else {
				model.setParameter("hidden", false);
			}
			
			model.setParameter("to.id", loginUserService.getLoginUser().getId());
		}
	    
	    PageInfo pageInfo = genericService.search(model, start, limit, sort, dir, newSearch, qlInfoRef);
	    String messageViewType = model.getParameter("messageViewType", String.class);
    	if (StringUtils.isEmpty(messageViewType)){
    		model.setParameter("messageViewType", MessageViewType.Normal.ordinal());
    	}
	    return pageInfo;
	}
	
	public void _add(@ParamScope(visible=false, value="#ps")PageElements ps){
		ps.safeElement("model.title").setRequired(true);
    	ps.safeElement("model.to.id").setRequired(true);
	}
	public void add(PPMessage model){
//		Model test = new Model();
//		test.setName("test");
//		ModelField mf = new ModelField();
//		mf.setName("aa");
//		mf.setModel(test);
//		test.safeModelFields().add(mf);
//		genericService.merge(test);
		
		model.setFrom(loginUserService.getLoginUser());
		model.setHidden(false);
		genericService.add(model);
	}
	
	public Result _update(@GenericType Object model) {
    	if (model == null) return null;
    	return getUpdateResult(model);
    }
	
	public Result getUpdateResult(@GenericType Object model) {
    	if (model == null) return null;
    	Integer id = ((Message)model).getId();
    	Message item = genericService.load(Message.class, id);
    	item = (Message) HibernateUtil.unproxy(item);
    	String param = "model.id=" + item.getId();
    	if (item instanceof WFMessage){
    		return urlUtil.getUrlResult(item.getClass(), "_accept", param);
    	} else {
    		return urlUtil.getUrlResult(item.getClass(), "_update", param);
    	}
    }
	
	public void deleteList(@GenericType List<Object> results) {
		for(Object obj : results){
			if (obj == null) continue;
			Message message = (Message)obj;
			if (message.getId() == null) continue;
			message = genericService.load(message);
			if (message instanceof WFMessage){
				
				if (message.getInstance() != null && message.getInstance().getSrcClassName() != null && message.getInstance().getSrcId() != null){
					WorkflowAware event = wfInstanceService.getSourceEntity(message.getInstance());
//					if (event.canDelete()){
						message.setHidden(true);
						genericService.update(message);
//					}
				}
			} else{
				message.setHidden(true);
				genericService.update(message);
			}
		}
	}
	
	// FIXME: Dummy code for test
	public void export() {
		printExcel();
	}
	// FIXME: Dummy code for test
	public void printExcel() {
		Map<String, Object> model = new HashMap<String, Object>();
		{
			Message message = new Message();
			LoginUser user = new LoginUser();
			user.setName("我的中文is Chinese test");
			message.setFrom(user);
			model.put("model", message);
		}
		PageInfo<Message> pageInfo = new PageInfo<Message>();
		List<Message> data = new ArrayList<Message>();
		{
			Message message = new Message();
			message.setId(null);		// test null value;
			message.setTitle("title1");
			message.setDescription("desc 1");
			data.add(message);
		}
		for (int i = 0; i < 9; i++) {
			Message message = new Message();
			message.setId(null);		// test null value;
			message.setTitle("title" + i);
			message.setDescription("描述 " + i);
			data.add(message);
		}
		pageInfo.setData(data);
		model.put("execute", pageInfo);
		
		Map<String, Integer> total = new HashMap<String, Integer>();
		total.put("totalId", 100);
		model.put("other", total);
		model.put("picture_0", "/static/espirit/images/default/login_bar.png");
		String url = config.getUploadDir() + "excelTpl/demo.xls";
		String demoExcel =   txFileService.checkAndGetRealFilePath(url);
		genericService.printExcel(model, demoExcel, Message.class.getSimpleName() + ".xls");
	}
}
